package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Formula;
import com.example.service.FormulaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/formulas")
public class FormulaController {

    @Autowired
    private FormulaService formulaService;


    /**
     * 公式信息展示
     * @param current  当前页
     * @param size     每页条数
     * @param formula   条件查询
     * @return
     */
    @GetMapping("{current}/{size}")
    public R<IPage> getPage(@PathVariable Integer current,@PathVariable Integer size,Formula formula){

        IPage page=new Page(current,size);

        LambdaQueryWrapper<Formula> lqw = new LambdaQueryWrapper<Formula>();
        lqw.like(Strings.isNotEmpty(formula.getName()),Formula::getName,formula.getName());

        IPage page1 = formulaService.page(page,lqw);

        return R.success("formula分页查询",page1);
    }

    /**
     * 新增公式
     * @param formula
     * @return
     */
    @PostMapping("/add")
    public R save(@RequestBody Formula formula){

        LambdaQueryWrapper<Formula> lqw =new LambdaQueryWrapper();
        lqw.eq(Strings.isNotEmpty(formula.getName()),Formula::getName,formula.getName());
        List<Formula> list = formulaService.list(lqw);

        if (list.size() <=0){
            formulaService.save(formula);

            return R.success("新增公式成功！",null);
        }else {
            return R.error("新增公式失败！"+formula.getName()+"已存在！");
        }
    }


    /**
     * 根据id修改公式信息()
     * @param formula
     * @return
     */
    @PutMapping("/updateFormula")
    public R update(@RequestBody Formula formula){

        formulaService.updateById(formula);

        return R.success("公式信息修改成功",formula);
    }


    /**
     * 通过id删除公式信息
     * @return
     */
    @DeleteMapping("/deleteFormula/{id}")
    public R deleteAdmin2(@PathVariable int id){

        boolean b = formulaService.removeById(id);
        if (b){
            return R.success("通过id删除公式信息成功",id);
        }else {
            return R.error("通过id删除公式信息失败！");
        }
    }


}
